package com.seecen.controller;

import com.seecen.cons.Cons;
import com.seecen.exception.AccountLockedException;
import com.seecen.exception.PasswordNotMatcherException;
import com.seecen.exception.UnknownUserException;
import com.seecen.pojo.Dictionary;
import com.seecen.pojo.UserInfo;
import com.seecen.pojo.UserMain;
import com.seecen.service.DictionaryService;
import com.seecen.service.UserService;
import com.seecen.utils.IdGenerator;
import com.seecen.utils.StringUtils;
import com.seecen.vo.IndexVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.util.List;

@Controller
@RequestMapping("/n")
public class UserController {

    @Autowired
    private DictionaryService dictionaryService;

    @Autowired
    private UserService userService;

    /**
     * 初始化注册页面
     *
     * @return
     */
    @RequestMapping("/registerInfo")
    public ModelAndView intiRegister() {
        ModelAndView mv = new ModelAndView("register");

        // 查询学历
        List<Dictionary> educationList = dictionaryService.findDictionarysByType(Cons.DICTIONARY_EDUCATION);
        // 查询月收入
        List<Dictionary> rangeList = dictionaryService.findDictionarysByType(Cons.DICTIONARY_SALARY_RANGE);
        // 查询省数据
        List<Dictionary> provinceList = dictionaryService.findProvinces();

        mv.addObject("educationList", educationList);
        mv.addObject("rangeList", rangeList);
        mv.addObject("provinceList", provinceList);

        return mv;
    }

    /**
     * 注册方法
     *
     * @param userMain 用户资料对象
     * @param userInfo 用户主要数据对象
     * @param request
     * @return 视图
     */
    @RequestMapping("/register")
    public ModelAndView register(UserMain userMain, UserInfo userInfo, HttpServletRequest request) {
        ModelAndView mv = new ModelAndView();

        boolean res = userService.save(userMain, userInfo);
        if (res) {
            request.getSession().setAttribute("userMain", userMain);
            mv.setViewName("redirect:/pages/login.jsp");
        } else {
            request.setAttribute("msg", "注册失败，用户名已存在！");
            return intiRegister();
        }
        return mv;
    }

    @RequestMapping("/login")
    public ModelAndView login(UserMain userMain, HttpSession session) {
        ModelAndView mv = new ModelAndView();
        try {
            userMain = userService.login(userMain);
            session.setAttribute(Cons.SESSION_USER_KEY, userMain);
            mv.setViewName("redirect:/pages/index.jsp");
        } catch (UnknownUserException e) {
            mv.addObject("msg", "用户名不存在");
        } catch (PasswordNotMatcherException e) {
            mv.addObject("msg", "密码错误");
        } catch (AccountLockedException e) {
            mv.addObject("msg", "账户状态异常");
        }
        return mv;
    }

    @RequestMapping("/myZhenai")
    public ModelAndView index(HttpSession session) {
        UserMain userMain = (UserMain) session.getAttribute(Cons.SESSION_USER_KEY);
        ModelAndView mv = new ModelAndView("index");
        // 查询当前登录未读的看过，消息，关注分别的数量
        IndexVo indexVo = userService.findIndexVo(userMain.getId());
        mv.addObject("indexVo", indexVo);
        return mv;
    }

    @RequestMapping("/face")
    public void face(HttpServletResponse response, HttpSession session, String facepath) {
        String realPath = session.getServletContext().getRealPath("/files");

        //创建一个file
        File newFile = new File(realPath, facepath);

        if (newFile.exists()) {
            try (InputStream is = new FileInputStream(newFile);
                 OutputStream os = response.getOutputStream();)
            {
                int len = 0;
                byte[] data = new byte[1024 * 512];
                while ((len = is.read(data)) != -1) {
                    os.write(data, 0, len);
                }
                os.flush();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @RequestMapping("/upload")
    public String upload(MultipartFile file, HttpSession session) throws IOException {
        // 获取项目运行的时候的真实全路径
        String realPath = session.getServletContext().getRealPath("/files");
        // 然后去找全路径+当月日期的文件夹
        File diskFile = new File(realPath + File.separator + StringUtils.getCurrentDate());
        // 如果这个目录不存在，就创建该目录（支持多层）
        if (!diskFile.exists()) {
            diskFile.mkdirs();
        }
        if (file != null && !file.isEmpty() && file.getSize() > 0) {
            // 在diskFile的文件夹内创建一个文件对象
            File f = new File(diskFile, buildName(file.getOriginalFilename()));
            f.createNewFile();
            // 把上传过来的二进制数据写入新文件中
            file.transferTo(f);
            UserMain userMain = (UserMain) session.getAttribute(Cons.SESSION_USER_KEY);
            String facepath = cutImagePath(f.getAbsolutePath());
            // 更新数据库的facepath
            userService.updateFace(userMain.getId(), facepath);
            // 更新session中的用户的头像
            userMain.setFacepath(facepath);
        }
        // 把成功上传的路径返回给前端
        return "redirect:/pages/uploadFace.jsp";
    }

    private String cutImagePath(String absolutePath) {
        absolutePath = absolutePath.replaceAll("\\\\", "/");
        int index = absolutePath.lastIndexOf("files/") + 6;
        String facepath = absolutePath.substring(index);
        return facepath;
    }


    private String buildName(String originalFilename) {
        IdGenerator idGenerator = new IdGenerator();
        Long id = idGenerator.snowflakeId();
        int index = originalFilename.lastIndexOf(".");
        return id + originalFilename.substring(index);
    }
}
